<?php
/**
 * Created by PhpStorm.
 * User: kuafu
 * Date: 2017/2/17
 * Time: 0:48
 */

namespace app\models;


require_once "../vendor/phpexcel/Classes/PHPExcel.php";

class ExcelReader
{
    private $_data = null;

    public function load($path)
    {
        $this->_data = $this->loadExcelData($path);
        return $this->_data;
    }

    public function getData()
    {
        return $this->_data;
    }

    public function parse()
    {

    }

    public function save()
    {
        $datetime = new \DateTime();
        $total = 0;
        foreach($this->_data as $row)
        {
            $total++;
            $huoke = new Huoke();
            $huoke->importDate = $datetime->format('Y-m-d H:i:s');
            $huoke->statusMessage = '';
            foreach($row as $key=>$value)
            {
                $huoke->setAttribute($key,$value);
            }
            $huoke->save();
        }
        return $total;
    }

    private function loadExcelData($path)
    {
        $objPHPExcel = \PHPExcel_IOFactory::load($path);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRowNum = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $highestColumnNum = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $filed = array();

        for($i=0; $i<$highestColumnNum;$i++){
            $cellName = \PHPExcel_Cell::stringFromColumnIndex($i).'1';
            $cellVal = $sheet->getCell($cellName)->getValue();//取得列内容
            $filed []= $cellVal;
        }

        //开始取出数据并存入数组
        $data = array();
        for($i=2;$i<=$highestRowNum;$i++){//ignore row 1
            $row = array();
            for($j=0; $j<$highestColumnNum;$j++){
                $cellName = \PHPExcel_Cell::stringFromColumnIndex($j).$i;
                $cell = $sheet->getCell($cellName);
                $cellVal = (string)$cell->getValue();

                if($filed[$j])
                {
                    if($filed[$j]=='applyDate')
                    {
                        $row[ $filed[$j] ] = gmdate("Y-m-d H:i:s", \PHPExcel_Shared_Date::ExcelToPHP($cellVal));
                    }
                    else
                    {
                        $row[ $filed[$j] ] = $cellVal;
                    }

                }

            }
            $data []= $row;
        }
        unset($sheet);
        unset($objPHPExcel);
        return $data;
    }
}